package cn.rkylin.oms.warehouse.stockDiff.controller;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.warehouse.stock.controller.StockController;
import cn.rkylin.oms.warehouse.stockDiff.dao.StockDiffDAOImpl;
import cn.rkylin.oms.warehouse.stockDiff.service.StockDiffService;
import cn.rkylin.oms.warehouse.stockDiff.vo.StockDiffVO;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import java.net.URLDecoder;
import com.github.pagehelper.PageInfo;
/**
 * Created by Administrator on 2018-3-28.
 */
@Controller
@RequestMapping("/stockDiff")
public class StockDiffController extends ApolloController {

    private static final String PAGE_SELECT_STATEMENT = "pageSelectStockDiff";
    private static final Log logger = LogFactory.getLog(StockController.class);

    @Autowired
    private StockDiffService stockDiffService;


    @ResponseBody
    @RequestMapping(value = "/showData")
    public Map<String, Object> showData(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
                                                  @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        Map map = new HashMap();
        try {

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser==null){
                map.put("result", "failed");
                map.put("msg", "用户不存在");
                return map;
            }
            if (currentUser.getCurrentProject()==null){
                map.put("result", "failed");
                map.put("msg", "用户的项目没设置");
                return map;
            }
            String projectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isBlank(projectId)){
                map.put("result", "failed");
                map.put("msg", "用户的项目没设置");
                return map;
            }

            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            StockDiffVO param = new StockDiffVO();
            if (!StringUtils.isEmpty(quickSearch)) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                param.setSearchCondition(quickSearch);
            }
            param.setProjectId(projectId);
            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
            if (mapItem!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                if (StringUtils.isBlank(mapItem.get("dateend")) && StringUtils.isBlank(mapItem.get("datestart"))){
                    map.put("result", "failed");
                    map.put("msg", "差异时间没有设置检索条件");
                    return map;
                }

                if (StringUtils.isNotBlank(mapItem.get("datestart"))){
                    param.setDatestart(sdf.parse(mapItem.get("datestart")));
                }

                if (StringUtils.isNotBlank(mapItem.get("dateend"))){
                    param.setDateend(sdf.parse(mapItem.get("dateend")));
                }

                if (StringUtils.isNotBlank(mapItem.get("storId"))){
                    param.setStorId(mapItem.get("storId"));
                }

                if (StringUtils.isNotBlank(mapItem.get("inventoryType"))){
                    param.setInventoryType(mapItem.get("inventoryType"));
                }
            } else {
                map.put("result", "failed");
                map.put("msg", "差异时间没有设置检索条件");
                return map;
            }
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("storType", "inventory_type");
            replaceFieldsMap.put("qtyDiff", "stock_qty - sell_count");

            // 排序语句生成
            String orderStatement = getOrderString(StockDiffDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            PageInfo<StockDiffVO> stockDiffVOList = stockDiffService.findByWhere(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put("recordsFiltered", stockDiffVOList.getTotal());
            map.put("recordsTotal", stockDiffVOList.getTotal());
            map.put(RETURN_DATA, stockDiffVOList.getList());

        } catch (Exception ex) {
            ex.printStackTrace();
            map.put("result", "failed");
            map.put("msg", ex.getMessage());
        }

        return map;
    }

    /**
     * 验证需要导出的条件
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/exportCheckDiff")
    public Map<String, Object> exportCheck(String formJson) throws Exception {
        logger.info("差异单check：/stockDiff/exportCheckDiff");
        Map<String, Object> returnJSON = new HashMap<String, Object>();
        try {
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null){
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, "查询当前登录人失败");
                return returnJSON;
            }

            // 获取当前登录人所属项目
            String projectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isBlank(projectId) || currentUser.getProjectMap() == null || currentUser.getProjectMap().size() <= 0) {
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, "查询当前登录人所属项目失败");
                return returnJSON;
            }

            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
            if (mapItem!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                if (StringUtils.isBlank(mapItem.get("dateend")) && StringUtils.isBlank(mapItem.get("datestart"))){
                    returnJSON.put("result", "failed");
                    returnJSON.put("msg", "差异时间没有设置检索条件");
                    return returnJSON;
                }

            } else {
                returnJSON.put("result", "failed");
                returnJSON.put("msg", "差异时间没有设置检索条件");
                return returnJSON;
            }

            // 上述check都没有错误的场合
            if (returnJSON.get(JSON_RESULT) == null) {
                returnJSON.put(JSON_RESULT, SUCCESS);
            }

        } catch (Exception ex){
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        return returnJSON;
    }

    /**
     * 导出
     * @param colName
     * @param colValue
     * @param quickSearch
     * @param formJson
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/exportDataDiff")
    public String exportData(String colName, String colValue, String quickSearch, String formJson) throws Exception {
        logger.info("差异单导出：/stockDiff/exportDataDiff");
        try {
            StockDiffVO param = new StockDiffVO();

            // 获取当前登录人
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                logger.error("差异单导出：/stockDiff/exportData,查询当前登录人失败");
                return null;
            }
            // 获取当前登录人所属项目
            String projectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isBlank(projectId) || currentUser.getProjectMap() == null || currentUser.getProjectMap().size() <= 0) {
                logger.error("差异单导出：/stockDiff/exportData,查询当前登录人所属项目失败");
                return null;
            }
            if (!StringUtils.isEmpty(quickSearch)) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                param.setSearchCondition(quickSearch);
            }
            param.setProjectId(projectId);
            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
            if (mapItem!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (StringUtils.isNotBlank(mapItem.get("datestart"))){
                    param.setDatestart(sdf.parse(mapItem.get("datestart")));
                }

                if (StringUtils.isNotBlank(mapItem.get("dateend"))){
                    param.setDateend(sdf.parse(mapItem.get("dateend")));
                }

                if (StringUtils.isNotBlank(mapItem.get("storId"))){
                    param.setStorId(mapItem.get("storId"));
                }

                if (StringUtils.isNotBlank(mapItem.get("inventoryType"))){
                    param.setInventoryType(mapItem.get("inventoryType"));
                }
            }
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("storType", "inventory_type");
            replaceFieldsMap.put("qtyDiff", "stock_qty - sell_count");

            param.setOrderBy("d.create_time,d.diff_code,d.stor_code,d.goods_code,d.sku_code");
//            // 排序语句生成
//            String orderStatement = getOrderString(StockDiffDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
//            if (StringUtils.isNotEmpty(orderStatement)) {
//                param.setOrderBy(orderStatement);
//            }

            PageInfo<StockDiffVO> stockDiffVOList = stockDiffService.findByWhere(0, Integer.MAX_VALUE, param);
            exportExcelFile(stockDiffVOList.getList(),colName,colValue,"差异单导出");

        } catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage());
        }
        return null;
    }
}
